package com.securitytrace.listener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;

import com.securitytrace.client.ManagerClient;
import com.securitytrace.dataModel.RoleDataModel;
import com.securitytrace.init.Init;
import com.securitytrace.model.Role;
import com.securitytrace.popupwindow.RoleWindow;

public class AddRoleButtonListener implements ActionListener {

	private RoleWindow roleWindow;
	
	public AddRoleButtonListener(RoleWindow roleWindow) {
		this.roleWindow = roleWindow;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		String name = roleWindow.getRoleTextField().getText();
		String desc = roleWindow.getRoleTextArea().getText();
		if(name.trim().isEmpty()) {
			JOptionPane.showMessageDialog(roleWindow, "角色名称不能为空");
		}else if(desc.trim().isEmpty()) {
			JOptionPane.showMessageDialog(roleWindow, "角色描述不能为空");
		}else {
			Role role = new Role();
			role.setName(name);
			role.setDescription(desc);
			try {
				addRoleToDatabase(role);
				roleWindow.dispose();
			} catch(Exception ex) {
				JOptionPane.showMessageDialog(roleWindow, "操作失败");
			}
		}
	}

	private void addRoleToDatabase(Role role) {
		Init.getRoleService().add(role);
		
		ManagerClient managerClient = roleWindow.getManagerClient();
		RoleDataModel roleDataModel = managerClient.getRoleModel();
		
		int currentPage = roleDataModel.getRoleCurrentPage();
		int pageSize = managerClient.getPageSize();
		int totalPage = 1;
		
		List<Role> roles = new ArrayList<Role>();
		roles = Init.getRoleService().getListByPage((currentPage - 1)  * pageSize, pageSize);
		
		long roleNumber = Init.getRoleService().getTotalCount();
		if((roleNumber % pageSize) == 0) {
			totalPage = (int) (roleNumber / pageSize);
		}else {
			totalPage = (int) (roleNumber / pageSize) + 1;
		}
		roleDataModel.setRoleTotal(totalPage);
		roleDataModel.setDataVector(roles);
		managerClient.getRolePanel().getRolePageInfoLabel().setText(roleDataModel.getRolePageInfo());
		System.out.println("add user");
	}
}
